<template>
  <div id="inovicePage">
    <BreadcrumbComponent :breadcrumbItems="breadcrumbItems" />
    <a-spin :spinning="loadingFilter">
      <TableFilter
        :config="filterConfig"
        @search="handleSearch"
        v-if="filterConfig"
      />
      <a-alert
        message="篩選欄"
        description="條件配置選項數據加載中"
        v-else
      ></a-alert>
    </a-spin>

    <!-- 工具欄 -->
    <a-space>
      <a-dropdown>
        <a-button type="primary" :loading="exportLoading">
          <template #icon>
            <ExportOutlined />
          </template>
          導出
        </a-button>
        <template #overlay>
          <a-menu @click="handleExport">
            <a-menu-item key="filteredData"> 按篩選導出 </a-menu-item>
            <a-menu-item key="allData"> 全部導出 </a-menu-item>
          </a-menu>
        </template>
      </a-dropdown>
    </a-space>
    <div class="data-box">
      <a-table
        :columns="columns"
        :data-source="tableData"
        :pagination="pagination"
        :loading="loading"
        :scroll="{ x: 1500, y: 450 }"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'shop'">
            {{ record.shopName }}({{ record.shopCode }})
          </template>

          <template v-if="column.dataIndex === 'staffCode'">
            {{ record.staffCode || "-" }}
          </template>

          <template v-if="column.dataIndex === 'pcard'">
            <span v-if="record.pcardCode"
              >{{ record.pcardName }}({{ record.pcardCode }})</span
            >
          </template>

          <template v-if="column.dataIndex === 'consultFlag'">
            <a-tag color="blue" v-if="record.consultFlag">是</a-tag>
            <a-tag v-else>否</a-tag>
          </template>
          <template v-if="column.dataIndex === 'consultShareClass'">
            <a-tag color="orange" v-if="record.consultShareClass === 1"
              >活動推廣</a-tag
            >
            <a-tag color="green" v-else-if="record.consultShareClass === 2"
              >自定義</a-tag
            >
            <a-tag color="cyan" v-else-if="record.consultShareClass === 3"
              >指定服務</a-tag
            >
            <a-tag color="blue" v-else-if="record.consultShareClass === 0"
              >默認</a-tag
            >
            <a-tag color="default" v-else>none</a-tag>
          </template>
          <template v-if="column.dataIndex === 'invoiceNet'">
            $ {{ record.invoiceNet.toLocaleString() }}
          </template>
          <template v-if="column.dataIndex === 'updatedAt'">
            {{ $formatDate(record.updatedAt) }}
          </template>
          <template v-if="column.key === 'action'">
            <a-button @click="handleView(record)">明細</a-button>
          </template>
        </template>
      </a-table>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, reactive } from "vue";
import { message } from "ant-design-vue";
import { ExportOutlined } from "@ant-design/icons-vue";
import BreadcrumbComponent from "@/components/BreadcrumbComponent.vue";
import TableFilter from "@/components/TableFilter.vue";
import {
  tableColumns,
  filterFields,
  getProcessFilterFields,
} from "@/models/invoice";
import { createPagination } from "@/utils/pagination";
import { invoiceApi } from "@/api";
import { useRouter, useRoute } from "vue-router";
import { watchRouteQuery } from "@/utils/routeQueryWatcherUtil";

const breadcrumbItems = [{ url: "", name: "醫單管理" }];
const columns = tableColumns;
const filterConfig = ref<any>(null);
const router = useRouter();
const route = useRoute();

const loadingFilter = ref(true);
onMounted(async () => {
  try {
    const config = await getProcessFilterFields();
    filterConfig.value = reactive(config);
  } catch (error) {
    console.error("加載篩選配置失敗:", error);
  } finally {
    loadingFilter.value = false;
  }
});

const loading = ref(false);

const pagination = createPagination();

const tableData = ref([]);

const fetchData = async (params?: any) => {
  loading.value = true; // 開始加載
  try {
    const {
      data: { list, page, limit, total },
    } = await invoiceApi.getInoviceList(params);
    tableData.value = list || [];
    pagination.updatePagination(page, limit, total);
  } catch (error) {
    console.error("獲取訂單列表失敗", error);
  } finally {
    loading.value = false; // 結束加載
  }
};

watchRouteQuery(fetchData);

const handleSearch = (params: any) => {
  if (params.inv_date) {
    params.inv_date_start = params.inv_date[0];
    params.inv_date_end = params.inv_date[1];
    delete params.inv_date;
  }
  router.push({ query: params });
};

const handleView = (record: any) => {
  // console.log(record.invNo)
  router.push({ name: "InvoiceDetail", params: { id: record.id } });
};

// 導出
const exportLoading = ref(false);
const handleExport = async ({ key }: { key: string }) => {
  let params: any = {};
  exportLoading.value = true;
  if (key === "filteredData") {
    params = route.query;
  }
  try {
    await invoiceApi.exportInoviceList(params);
  } catch (error) {
    message.error("導出數據失敗");
  } finally {
    exportLoading.value = false;
  }
};
</script>

<style scoped></style>
